# Maintainer: Jelle van der Waa <jelle@archlinux.org>
# Contributor: Sebastian Zwierzchowski <seba@angrysoft.ovh>

pkgname=zigbee2mqtt
pkgver=1.30.4
pkgrel=1
pkgdesc='A Zigbee to MQTT bridge'
arch=('loong64' 'x86_64')
url='https://www.zigbee2mqtt.io'
license=('GPL3')
depends=('nodejs-lts-hydrogen') # FS#75807
makedepends=('typescript' 'npm')
backup=('etc/zigbee2mqtt/configuration.yaml')
optdepends=('mosquitto: MQTT broker')
options=(!emptydirs)
source=(${pkgname}-${pkgver}.tar.gz::"https://github.com/Koenkk/${pkgname}/archive/${pkgver}.tar.gz" 'zigbee2mqtt.service'
  	'zigbee2mqtt.sysusers' 'zigbee2mqtt.tmpfiles')
sha256sums=('cc02bdf9d34a09016c60a6abdd4e2c0a3ce561ddc5186d989c34b1d4aacaea28'
            '04d58763942cc598ac858f003b174316b695c2a542b2788e50751c3077adf106'
            '3a86716e9036e97d885e9b5f37c7f87d9c2872435e4acf9fc4c9157264cf387b'
            'b8cb53b06176abb09e74e68daee702263f3d471b249c51b1b32d693fc7354fd8')

build() {
  cd "${pkgname}-${pkgver}"
  npm install
  NODE_ENV=production npm run build
  npm prune --production
}

package() {
  cd "${pkgname}-${pkgver}"
  install -m0755 -d "${pkgdir}/usr/share/webapps/${pkgname}"
  cp -a node_modules dist "${pkgdir}/usr/share/webapps/${pkgname}"

  install -m0644 cli.js -t "${pkgdir}/usr/share/webapps/${pkgname}"
  install -m0644 index.js -t "${pkgdir}/usr/share/webapps/${pkgname}"
  install -m0644 package.json -t "${pkgdir}/usr/share/webapps/${pkgname}"

  # sanitize permissions
  find "${pkgdir}/usr" -type d -exec chmod 755 {} +
  chown -R root:root "${pkgdir}"

  install -Dm644 data/configuration.yaml "${pkgdir}/etc/${pkgname}/configuration.yaml"

  install -Dm644 "${srcdir}/${pkgname}.service" "${pkgdir}/usr/lib/systemd/system/${pkgname}.service"
  install -Dm644 "${srcdir}/${pkgname}.sysusers" "${pkgdir}/usr/lib/sysusers.d/${pkgname}.conf"
  install -Dm644 "${srcdir}/${pkgname}.tmpfiles" "${pkgdir}/usr/lib/tmpfiles.d/${pkgname}.conf"

  # Cleanups x86_64 specific
  if [ "${CARCH}" = "x86_64" ]; then
    local find_dirs=(
    -iwholename '*.github' -o
    -iwholename '*.idea' -o
    -iwholename '*.tscache' -o
    -iwholename '*/man' -o
    -iwholename '*/test' -o
    -iwholename '*/scripts' -o
    -iwholename '*/git-hooks' -o
    -iwholename '*/android-arm' -o
    -iwholename '*/android-arm64' -o
    -iwholename '*/linux-arm64' -o
    -iwholename '*/linux-armvy' -o
    -iwholename '*/linux-armv7' -o
    -iwholename '*/linux-arm' -o
    -iwholename '*/win32-ia32' -o
    -iwholename '*/win32-x64' -o
    -iwholename '*/darwin-x64'
    )

    find ${pkgdir}/usr/share/webapps/${pkgname}/node_modules -type d \( "${find_dirs[@]}" \) -exec rm -rvf {} +
  fi

}
